package handler

import (
	"strconv"

	"github.com/gin-gonic/gin"

	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
	"awesomeProject/app/verify"
	"awesomeProject/util"
)

type MenuHandler struct{}

var menuSrv service.MenuSrv

func (r *MenuHandler) MenuTree(ctx *gin.Context) {
	response.Result(ctx, menuSrv.MenuTree())
	return
}

func (r *MenuHandler) Create(ctx *gin.Context) {
	var req request.MenuCreate
	_ = ctx.Bind(&req)
	// 表单校验
	if err := verify.MenuCreate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	uid := util.CurrentLoginUid(ctx)
	// 执行创建
	response.Result(ctx, menuSrv.Create(model.MenuFillAble{
		Pid:       req.Pid,
		Name:      req.Name,
		Type:      req.Type,
		Icon:      req.Icon,
		Link:      req.Link,
		Sort:      req.Sort,
		CreatedBy: uid,
	}))
	return
}

func (r *MenuHandler) Show(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, menuSrv.Show(uint(id)))
	return
}

func (r *MenuHandler) Update(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	var req request.MenuUpdate
	_ = ctx.Bind(&req)
	if err := verify.MenuUpdate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	uid := util.CurrentLoginUid(ctx)
	req.UpdatedBy = uid
	response.Result(ctx, menuSrv.Update(uint(id), req))
	return
}

func (r MenuHandler) Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, menuSrv.Del(uint(id)))
	return
}
